package bankingSystemServer;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * a thread to listen to clients
 */
public class ServerListeningThread extends Thread {
	private static int numberOfRunningThreads = 0;
	private int threadNumber;
	private boolean running;
	private Server parent;
	private Socket socket;

	public ServerListeningThread(Socket socket, Server parent) {
		running = true;
		this.parent = parent;
		this.socket = socket;
	}

	public void run() {
		numberOfRunningThreads++;
		threadNumber = numberOfRunningThreads;
		System.out.println("Listening thread " + threadNumber + " created.");
		try {
			ObjectOutputStream out = new ObjectOutputStream(socket
					.getOutputStream());
			ObjectInputStream in = new ObjectInputStream(socket
					.getInputStream());
			while (running) {
				Object request = in.readObject();
				parent.receiveMessage(request, out, this);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("Listening thread " + threadNumber + " finished.");
		numberOfRunningThreads--;
	}

	/**
	 * called by the server to stop the thread
	 */
	public void stopRunning() {
		running = false;
	}
}
